package com.tunan.system.att.web;

import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;


import java.util.ArrayList;
import java.util.List;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.tunan.system.att.utils.BscAttForm;
import com.tunan.utils.AttUtils;
import com.tunan.utils.FileImages;
import com.tunan.utils.JsonUtils;

/**
 * 附件管理控制器
 * @author Administrator
 *
 */
@Controller
@RequestMapping("/BscAtt")
public class BscAttController extends BscBaseAttController{
	
	
    /**
     * 附件批量上传
     * @param attachment 附件文件
     * @param form 附件模型
     * @param response 页面响应
     * @return 返回上传结果 
     * @throws IOException 抛出错误
     */
	@RequestMapping(value = "/uploadForSwfupload.do", method = RequestMethod.POST)
	@ResponseBody 
	public String uploadForSwfupload(MultipartFile attachment,
			@ModelAttribute("form") BscAttForm form,HttpServletResponse response,
			HttpServletRequest request) throws Exception {
		try {
			//throw new NullPointerException("testeeee");
			boolean ret=super.uploadFile(form.getTableName(),form.getPkName(),form.getRecordId(),form.getAttPath(),form.getOrgSeq(),form.getIsRelative(),form.getAttCode(),form.getAttName(),form.getAttType(),form.getIsDbStore(),form.getIsEncrypt(),form.getEncryptClass(),attachment);
			if(ret){
				response.getWriter().print("successed");
				if(logger.isDebugEnabled()){
					logger.debug("执行附件上传成功。");
				}
			}
			return null;
		}catch (Exception e) {
			logger.error("上传附件出错,上传附件的form:{}。",JsonUtils.toJson(form));
			throw e;
		}
	}

	/**
	 * 附件读取
	 * @param id 附件Id
	 * @param response 响应
	 * @param request 请求
	 * @return 返回下载的数据
	 */
	@RequestMapping("/read.do")
	public void read(String id, HttpServletResponse response,
			HttpServletRequest request) throws Exception{
			BscAttForm form =null; //this.bscAtService.findById(id);
			if(this.downFile(form, response, request)){
				 if(logger.isDebugEnabled()){
					logger.debug("执行单个附件下载成功。");
				 }
			 }
	}
	private void setExistPro(List<BscAttForm> formList) {
		String attPath;
		for(BscAttForm form:formList){
			attPath=form.getAttPath();
			if("0".equals(form.getIsDbStore())){
				if("1".equals(form.getIsRelative())){
					attPath = getRequest().getRealPath("/") + "\\" + attPath;
				}
				if(!new File(attPath + "\\" + form.getAttCode()+"."+form.getAttFormat()).exists()){
					form.setExistFile("0");
				}
			}
		}
	}
	
	/**
	 * NTKO上传文档至服务器磁盘并更新文档附件记录
	 * @param form 附件模型
	 * @param document 文件流
	 * @param response 响应
	 * @return 返回上传结果 
	 * @throws Exception 错误
	 */
	@RequestMapping(value = "/upload.do", method = RequestMethod.POST)
	public void upload(BscAttForm form,MultipartFile document,HttpServletResponse response) throws Exception{
		if(form.getId()!=null&&form.getId().trim().length()>0){
			form=null;//this.bscAtService.findById(form.getId());
		}
		boolean success = this.uploadFile(form, document);
		if(success){
			response.getWriter().print("successed");
			if(logger.isDebugEnabled()){
				logger.debug("成功保存文件，文件信息form:{}。",JsonUtils.toJson(form));
			}
		}else{
			response.getWriter().print("failed");
			if(logger.isDebugEnabled()){
				logger.debug("保存文件失改，文件信息form:{}。",JsonUtils.toJson(form));
			}
		}
	}
//－－－－－－－－－－使用完－－－－－	

	
//注释:下面的设计由于打开编辑时经转递很多参数比如查询条件、排序由于每个业务的查询条件不同会使浏览上一、下一组件失去通用性。
//	/**
//	 * 新增附件
//	 * @param attachment 附件
//	 * @param form 附件模型
//	 * @param redirectUrl 重定向的url
//	 * @return 重定向url
//	 * @throws IOException 抛出错误
//	 */
//	@RequestMapping(value = "/add.do", method = RequestMethod.POST)
//	public String add(@RequestParam(value = "attachment", required = false)
//			MultipartFile attachment,@ModelAttribute("form") BscAttForm form,String redirectUrl) throws IOException {
//		this.uploadFile(form.getTableName(),form.getPkName(),form.getRecordId(), null,null, null, null,null,null,null,null, attachment);
//		return "redirect:"+redirectUrl;
//	}
	

//
//	/**
//	 * ajax方式获取上一个office文档附件Id
//	 * @param form 附件模型
//	 * @return 返回上一个附件ID
//	 */
//	@RequestMapping("/getPreId.do")
//	@ResponseBody
//	public String getPreId(BscAttForm form){
//		if(form.getId()!=null){
//			String result=this.bscAtService.getPreId(form);
//			if(result!=null){
//				return this.bscAtService.getPreId(form);
//			}
//		}
//		return null;
//	}
//	
//	/**
//	 * ajax方式获取下一个office文档的附件Id
//	 * @param form 附件模型
//	 * @return 返回下一个附件Id
//	 */
//	@RequestMapping("/getNextId.do")
//	@ResponseBody
//	public String getNextId(BscAttForm form){
//		if(form.getId()!=null){
//			String result=this.bscAtService.getNextId(form);
//			if(result!=null){
//				return this.bscAtService.getNextId(form).toString();
//			}
//		}
//		return null;
//	}
	
	/**
	 * 附件后台主界面
	 *@return 附件后台管理页面
	 */
	@RequestMapping("/attMgmtIndex.do")
	public String attMgmtIndex() {
		return "/bsc/att/bscAttMgmtIndex";
	}
	
	//--------------auth:附件权限配置---------
	/**
	 * 附件配置列表
	 * @return
	 */
	@RequestMapping("/attAuthIndex.do")
	public String attAuthIndex(){
		if(logger.isDebugEnabled()){
			logger.debug("系统打开附件配置页面。");
		}
		return "/bsc/att/bscAttAuthIndex";
	}
	/**
	 * 获取默认文件图标
	 * @param id 附件Id
	 * @param response 响应
	 * @param request 请求
	 * @return 返回下载的数据
	 */
	@RequestMapping("/icon.do")
	public void icon(String ext, HttpServletResponse response) throws Exception{
		if(StringUtils.isEmpty(ext))return;
		ServletOutputStream out=null;
		ByteArrayInputStream input=null;
		try {
			response.setContentType("image/png");
			input= new ByteArrayInputStream(FileImages.get(ext));    
			/*temp*/
			String path=File.listRoots()[0].getAbsolutePath()+"/";
			File tempFile=new File(path+"//sfiletype/"+ext+".png");
			if(!tempFile.exists()){
				if(!new File(path+"//sfiletype/").exists()){
					new File(path+"//sfiletype/").mkdirs();
				}
			OutputStream	outtemp=new FileOutputStream(tempFile);
    		byte[] buffer = new byte[BUFFER_SIZE];
        	int available= 0;
        	while ((available= input.read(buffer)) != -1) {
        		if (available < BUFFER_SIZE) {
        			outtemp.write(buffer, 0, available);
        		} else {
        			outtemp.write(buffer, 0, BUFFER_SIZE);
        		}
        	}
        	outtemp.close();
        	}
        	/*temp over*/
			input.reset();
			BufferedImage bx=ImageIO.read(input);
			out = response.getOutputStream() ;
			ImageIO.write(bx, "png",out);
		 }catch (Exception e) {
			logger.error("获取图标出错,扩展名:{}。", ext);
			throw e;
		 }finally{
			 try {
				 if(input!=null){
					 input.close();
					 }
				 if(out!=null){
					 out.close();
				 }
			} catch (Exception e2) {
			}
		 }
	}
	/**
	 * 获取文件大图标
	 * @param id 附件Id
	 * @param response 响应
	 * @param request 请求
	 * @return 返回下载的数据
	 */
	@RequestMapping("/iconBig.do")
	public void iconBig(String ext, HttpServletResponse response) throws Exception{
		if(StringUtils.isEmpty(ext))return;
		ServletOutputStream out=null;
		ByteArrayInputStream input=null;
		try {
			response.setContentType("image/png");
			input= new ByteArrayInputStream(FileImages.getBig(ext));   
			/*temp*/
			File tempFile=new File("D://bfiletype/"+ext+".png");
			if(!tempFile.exists()){
				if(!new File("D://bfiletype/").exists()){
					new File("D://bfiletype/").mkdirs();
				}
			OutputStream	outtemp=new FileOutputStream(tempFile);
    		byte[] buffer = new byte[BUFFER_SIZE];
        	int available= 0;
        	while ((available= input.read(buffer)) != -1) {
        		if (available < BUFFER_SIZE) {
        			outtemp.write(buffer, 0, available);
        		} else {
        			outtemp.write(buffer, 0, BUFFER_SIZE);
        		}
        	}
        	outtemp.close();
        	}
			input.reset();
        	/*temp over*/
			BufferedImage bx=ImageIO.read(input);
			out = response.getOutputStream() ;
			ImageIO.write(bx, "png",out);
		}catch (Exception e) {
			logger.error("获取图标出错,扩展名:{}。", ext);
			throw e;
		}finally{
			try {
				if(input!=null){
					input.close();
				}
				if(out!=null){
					out.close();
				}
			} catch (Exception e2) {
			}
		}
	}
	//--------------big file:大附件上传初始化页面---------
	/**
	 * 进入大附件上传初始化页面
	 * @return
	 */
	@RequestMapping("/uploaderfile.do")
	public String uploaderfile(){
		if(logger.isDebugEnabled()){
			logger.debug("进入大附件上传初始化页面页面。");
		}
		return "/bsc/att/ntkolfupload/uploaderfile";
	}
	/**
	 * 向服务器查询上传文件状态信息的url
	 * @return
	 */
	@RequestMapping("/queryfilestatus.do")
	public String queryfilestatus(){
		if(logger.isDebugEnabled()){
			logger.debug("进入大附件上传初始化页面页面。");
		}
		return "/bsc/att/ntkolfupload/queryfilestatus";
	}
	/**
	 * 文件上传完成以后需要后台做的善后处理url
	 * @return
	 */
	@RequestMapping("/finishedupload.do")
	public String finishedupload(){
		if(logger.isDebugEnabled()){
			logger.debug("进入大附件上传初始化页面页面。");
		}
		return "/bsc/att/ntkolfupload/finishedupload";
	}
}

